package com.ghostbusters.fingertrack.match;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.ghostbusters.fingertrack.application.Keyboard;
import com.ghostbusters.fingertrack.calibration.Calibration;
import com.ghostbusters.fingertrack.calibration.Signature;
import com.ghostbusters.fingertrack.recognition.Recognizer;
import com.ghostbusters.fingertrack.wii.IRPoint;
import com.ghostbusters.fingertrack.wii.WiiMain;
import com.ghostbusters.fingertracker.util.MapUtil;

public class ApplicationMatcher<E> extends Matcher<E> {

	public ApplicationMatcher(Calibration<E> calibration) {
		setCalibration(calibration);
		setRecognizer(new Recognizer<E>());
		setSignature(new Signature());

		WiiMain.subscribe(this);
	}

	@Override
	public void newPoints(List<IRPoint> irPoints) {

		if (irPoints.size() == 1) {
			/*
			 * getSignature().addPoint(irPoints.get(0)); Object match =
			 * getRecognizer().match(getCalibration(), getSignature()); if(
			 * match != null) { // Keyboard.type((Character)match); }
			 */
			getSignature().addPoint(
					new IRPoint(irPoints.get(0).getX()
							* Calibration.CALIBRATION_SIZE, irPoints.get(0)
							.getY() * Calibration.CALIBRATION_SIZE));
			double min = Double.MAX_VALUE;
			Map<Character, Double> value = null, lastVal = null;
			int counter = 0;
			for (int i = 0; i < getSignature().getList().size() - 20; i = i + 5) {
				List list = (new MapUtil()).splitFrom(getSignature().getList(),
						0);
				Signature sig = new Signature();
				sig.setList(list);

				value = (new MapUtil<Character>()).findMin(new MapUtil()
						.findBelowThreshold(
								getRecognizer().match(getCalibration(), sig),
								0.2));
				if (lastVal != null) {
					for (Character c : lastVal.keySet()) {
						if (value.get(c) != null) {
							counter++;
							if (counter == 5) {
								setSignature(new Signature());
								Keyboard.type(c);
								System.out.println(c);

							}
						} else {
							counter = 0;
						}
					}
				}
				if (!value.isEmpty())
					for (Character object : value.keySet()) {
						try {
							if (value.get(object) < min) {
								min = value.get(object);
								value = new HashMap<Character, Double>();
								value.put(object, min);
							}
						} catch (Throwable e) {

						}
					}
				lastVal = value;
			}

		}
	}
}
